package server.threads;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;

import server.GameServer;
import server.constants.OutgoingConstants;

/**
 * This thread is used by a GameServer to handle any outgoing messages to a user
 * that is currently in the game. This is primarily used to send updates on the
 * game's state such as the positions of all players and the ball.
 */
public class GameServerOutgoing extends Thread {
	public static final int UPDATE_INTERVAL = 50;
  	private PrintWriter out;
  	private GameServer gameServer;
  	
  	public GameServerOutgoing(String name, Socket socket, GameServer gameServer) {
  		super(name);
  		this.gameServer = gameServer;
  		
  		try {
			out = new PrintWriter(socket.getOutputStream(), true);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
  	}
  	
  	public void run() {		
  		while(true) {
  			try {
				Thread.sleep(UPDATE_INTERVAL);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
  			
  			out.println("{\"type\":" + OutgoingConstants.GAMESERVER_UPDATE + ",\"gameServer\":" + gameServer.toJson() + "}");
  			if(!gameServer.getPlayers().containsKey(getName())) {
  				break;
  			}
  		}
  		
  		System.out.println(getName() + " has left GameServer " + gameServer.getName());
  	}
}
